﻿<%
'''以Application方式实现的缓存驱动类
Class AshapoCacheDriverApplication

	'''缓存标识前缀
	Private s_prefix
	
	'''缓存有效期（单位为秒）,为0表示永久有效
	Private s_expire
	
	'''限制缓存的数量,为0不限制
	Private s_length
	
	'内部使用AshapoConfig对象
	Private s_cfg
	
	'''构造
	Private Sub Class_Initialize()
		Set s_cfg = New AshapoConfig
	End Sub
	
	'''析构
	Private Sub Class_Terminate()
		Set s_cfg = Nothing
	End Sub
	
	'''初始化
	'p_expire:缓存有效期（单位为秒）,为0表示永久有效
	'p_prefix:缓存标识前缀
	'p_length:限制缓存的数量
	Public Sub Init(Byval p_expire, Byval p_prefix, Byval p_length)
		s_prefix = p_expire
		s_expire = p_prefix
		s_length = p_length
		Dim t_x
		For Each t_x In Application.Contents
			If InStr(t_x, s_prefix) = 1 Then
				If DateDiff("s", Now(), Application.Contents(t_x)("expire")) > 0 Then
					Application.Contents.Remove(t_x)
				End If
			End If
		Next
		'todo 可能误删其他Application
		If Application.Contents.Count > s_length Then
			Application.Contents.Remove(0)
		End If
	End Sub
	
	'''设置缓存过期时间
	'p_expire:有效时间（单位为秒）
	Public Property Let Expire(Byval p_expire)
		s_expire = p_expire
	End Property
	
	'''设置缓存标识前缀
	'p_prefix:缓存标识前缀
	Public Property Let Prefix(Byval p_prefix)
		s_prefix = p_prefix
	End Property
	
	'''限制缓存的数量
	'''todo 准备舍弃
	'p_length:最大缓存的数量
	Public Property Let [Length](Byval p_length)
		If ( p_length > 100 Or p_length = 0 ) Then
			p_length = 100 ''Application由于是内存缓存，不能过多
		End If
		s_length = p_length
	End Property
	
	'''存储缓存
	Public Property Let Value(Byval p_key, Byval p_value)		
		Dim t_item : Set t_item = Server.CreateObject( s_cfg.Environment("Scripting.Dictionary") )
		If IsObject(p_value) Then
			Set t_item("value") = p_value
		Else
			t_item("value") = p_value
		End If
		
		If s_expire > 0 Then
			t_item("expire") = DateAdd("s", s_expire, Now())
		End If
		Application.Lock()
		Set Application( s_prefix & p_key ) = t_item
		Application.Unlock()
	End Property
	
	'''取回缓存,默认
	Public Default Property Get Value(Byval p_key)
		Dim t_full_key : t_full_key = s_prefix & p_key
		If IsN( Application(t_full_key) ) Then
			Value  = vbNull
			Exit Property
		End If
		If TypeName( Application(t_full_key) ) <>  "Dictionary" Then
			Value  = vbNull
			Exit Property
		End If
		Dim t_item : Set t_item = Application(t_full_key)
		If Has(t_item("expire")) Then
			If DateDiff("s", Now(), t_item("expire")) > 0 Then
				Application.Contents.Remove(t_full_key)
				Value  = vbNull
				Exit Property
			End If
		End If
		If IsObject(t_item("value")) Then
			Set Value = t_item("value")
		Else
			Value = t_item("value")
		End If
	End Property
	
	'''删除指定缓存
	Public Sub Remove(Byval p_key)
		Application.Contents.Remove(p_key)
	End Sub
	
	'''清理缓存
	Public Sub RemoveAll()
		Dim t_x
		For Each t_x In Application.Contents
			If InStr(t_x, s_prefix) = 1 Then
				Application.Contents.Remove(t_x)
			End If
		Next
	End Sub
End Class
%>